package com.jzd.fwserver

import com.jzd.fwserver.util.Config
import com.jzd.fwserver.util.toHexString
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.socket.DatagramPacket
import io.netty.handler.codec.MessageToMessageDecoder

class Decoder : MessageToMessageDecoder<DatagramPacket>()
{

    private fun check(msg: ByteBuf): ByteArray?
    {
        if (msg.readableBytes() < 27) {
            return null
        }
        var found = false
        loop@ while (msg.readableBytes() > 2) {
            msg.markReaderIndex()
            if (msg.readByte() == 0xA5.toByte()) when (msg.readByte()) {
                0x5A.toByte() -> {
                    found = true; break@loop
                }
                0xA5.toByte() -> {
                    msg.resetReaderIndex().readByte()
                }
            }
        }
        if (!found) {
            return null
        }
        val dataLen = msg.readShortLE()
        msg.resetReaderIndex().markReaderIndex()
        if (dataLen + 27 > msg.readableBytes()) {
            msg.resetReaderIndex()
            return null
        }
        val buffer = ByteArray(dataLen + 27)
        msg.readBytes(buffer)
        return buffer
    }

    override fun decode(ctx: ChannelHandlerContext, datagramPacket: DatagramPacket, p2: MutableList<Any>?)
    {
        val buffer = check(datagramPacket.content())
        buffer?.let {
            Config.sender = datagramPacket.sender()
            println("[received]:${buffer.toHexString()}")
            println(Config.sender.toString())
        }
    }
}